#include "mainWindow.h"
#include "myEvent.h"

#include <QtGui/QAction>
#include <QtGui/QMenuBar>
#include <QtGui/QMenu>
#include <QtGui/QToolBar>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QLabel>
#include <QtGui/QtGui>
#include <QtGui/QMouseEvent>

const QEvent::Type MYCOSTOMEVEVT= (QEvent::Type)5001;

MainWindow::MainWindow(QWidget* parent /* = 0 */)
	:QMainWindow(parent),
	m_openAction(NULL),
	m_msgLabel(NULL)
{
	resize(800, 600);

	m_openAction = new QAction(tr("Open"), this);
	m_openAction->setShortcut(QKeySequence::Open);
	m_openAction->setStatusTip(tr("Open a file"));
	connect(m_openAction, SIGNAL(triggered()), this, SLOT(openFile()));

	QMenu* file = menuBar()->addMenu(tr("&File"));
	file->addAction(m_openAction);

	QToolBar* toolbar = addToolBar(tr("&File"));
	toolbar->addAction(m_openAction);

	m_msgLabel = new QLabel(this);
	m_msgLabel->setMinimumSize(m_msgLabel->sizeHint());
	m_msgLabel->setAlignment(Qt::AlignCenter);

	statusBar()->addWidget(m_msgLabel);

	QObject::installEventFilter(this);

	//QApplication::postEvent(this, new MyEvent((QEvent::Type)QEvent::registerEventType(MYCOSTOMEVEVT)));
}

MainWindow::~MainWindow()
{

}

void MainWindow::openFile()
{
	QString filepath = QFileDialog::getOpenFileName(this, tr("Open File"), ".", tr("C++ files(*.h *.cpp)"));
	if (!filepath.isEmpty())
		QMessageBox::information(NULL, tr("File Open"), tr("you select: ") + filepath);
}

void MainWindow::mouseDoubleClickEvent(QMouseEvent *pEvent)
{
	if (pEvent->button() == Qt::LeftButton)
		this->setWindowTitle(tr("Double clicked"));
	
	QMainWindow::mouseDoubleClickEvent(pEvent);
}

bool MainWindow::eventFilter(QObject *pObj, QEvent *pEvent)
{
	if (pObj == this)
	{
		if (pEvent->type() == QEvent::KeyPress)
		{
			QKeyEvent *pKeyEvent = static_cast<QKeyEvent*>(pEvent);
			quint32 key = pKeyEvent->nativeVirtualKey();
			QString str;
			QMessageBox::about(NULL, tr("Key"), str.sprintf("Key: %d", key));
			return true;
		}
	}
	return QMainWindow::eventFilter(pObj, pEvent);
}

void MainWindow::customEvent(QEvent *pEvent)
{
	if (pEvent->type() == MYCOSTOMEVEVT)
	{
		MyEvent* pE = static_cast<MyEvent*>(pEvent);
		QMessageBox::information(NULL, tr("Msg"), tr("My event"));
	}
}

void MainWindow::paintEvent(QPaintEvent *pEvent)
{
	QPainter painter(this);
	painter.setPen(Qt::blue);
	painter.drawText(50, 50, tr("<h3>Hello World!</h3>"));

	QMainWindow::paintEvent(pEvent);
}